#include <sys/time.h>
#include <iostream>
#include <unistd.h>
#include <sys/socket.h>

using namespace std;


/*

  this function is used to recv from a socket.
  if seconds is passed, it will disconnect.
  this function came from nmap.
*/
int recvtime(int sd, char *buf, int len, int seconds, int *timedout)
{
  int res;
  struct timeval timeout;
  fd_set readfd;

  timeout.tv_sec = seconds;
  timeout.tv_usec = 0;
  FD_ZERO(&readfd);
  FD_SET(sd, &readfd);
  if (timedout) *timedout = 0;
  res = select(sd + 1, &readfd, NULL, NULL, &timeout);
  if (res > 0 ) {
    res = recv(sd, buf, len, 0);
    if (res >= 0) return res;
    return 0;
  }
  else if (!res) {
    if (timedout) *timedout = 1;
    cout << "timeout" << endl;
    return 0;
  }
  cout << "error" << endl;
  return -1;

}
